package com.example.demo.service.impl;

import com.example.demo.entity.Book;
import com.example.demo.repository.BookRepository;
import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 图书服务实现类
 * @author Logan.Li
 */
@Service
public class BookServiceImpl implements BookService {
    
    @Autowired
    private BookRepository bookRepository;
    
    @Override
    @Transactional
    public Book saveBook(Book book) {
        try {
            System.out.println("保存图书: " + book.getTitle());
            Book savedBook = bookRepository.save(book);
            System.out.println("保存成功，ID: " + savedBook.getId());
            return savedBook;
        } catch (Exception e) {
            System.out.println("保存图书失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    @Override
    public Optional<Book> findById(Long id) {
        return bookRepository.findById(id);
    }
    
    @Override
    public List<Book> findAll() {
        return bookRepository.findAll();
    }
    
    @Override
    public Page<Book> findAll(Pageable pageable) {
        return bookRepository.findAll(pageable);
    }
    
    @Override
    public List<Book> findByTitle(String title) {
        return bookRepository.findByTitleContaining(title);
    }
    
    @Override
    public List<Book> findByAuthor(String author) {
        return bookRepository.findByAuthor(author);
    }
    
    @Override
    public List<Book> findByCategory(String category) {
        return bookRepository.findByCategory(category);
    }
    
    @Override
    public Book findByIsbn(String isbn) {
        return bookRepository.findByIsbn(isbn);
    }
    
    @Override
    @Transactional
    public void deleteById(Long id) {
        bookRepository.deleteById(id);
    }
}
